
<?php
class WechatApi 
{
	public $appid = '';
	public $appsecret = '';
	public $error = array();
	public function __construct($config) 
	{
		import('checkFunc', './source/class/');
		$checkFunc = new checkFunc();
		if (!function_exists('qeuwr801nvs9u21jk78y61lkjnc98vy245n')) 
		{
			exit('error-4');
		}
		$checkFunc->qeuwr801nvs9u21jk78y61lkjnc98vy245n();
		$this->appid = $config['appid'];
		$this->appsecret = $config['appsecret'];
	}
	public function get_access_token($type = 0) 
	{
		$access_obj = D('Access_token_expires')->where('1')->find();
		$now = intval(time());
		if (!$this->checkTokenExpires($access_obj['access_token']) && $access_obj && (($now - 1200) < intval($access_obj['expires_in']))) 
		{
			return array('errcode' => 0, 'access_token' => $access_obj['access_token']);
		}
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . trim($this->appid) . '&secret=' . trim($this->appsecret);
		$json = json_decode($this->curlGet($url));
		if ($json->errmsg) 
		{
			return array('errcode' => $json->errcode, 'errmsg' => $json->errmsg);
		}
		if ($access_obj) 
		{
			D('Access_token_expires')->where(array('id' => $access_obj['id']))->data(array('access_token' => $json->access_token, 'expires_in' => intval($json->expires_in + $now)))->save();
		}
		else 
		{
			D('Access_token_expires')->data(array('access_token' => $json->access_token, 'expires_in' => intval($json->expires_in + $now)))->add();
		}
		return array('errcode' => 0, 'access_token' => $json->access_token);
	}
	public function checkTokenExpires($token) 
	{
		$url_get = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=' . $token;
		$res = json_decode($this->curlGet($url_get), true);
		if (($res['errcode'] == '40013') || ($res['errcode'] == '40001') || ($res['errcode'] == '42001')) 
		{
			return true;
		}
		return false;
	}
	public function curlGet($url) 
	{
		$ch = curl_init();
		$header = array('Accept-Charset: utf-8');
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$temp = curl_exec($ch);
		return $temp;
	}
}
?>